// 下载小程序二维码的工具js
import request from 'request';
import { WX_ACCOUNT_APPID, WX_ACCOUNT_APP_SECRET, WX_MINIPROGRAM_APP_ID, WX_MINIPROGRAM_SECRET } from '../../config';
import redis from '../redis';

const WXAPP_TOKEN_REDIS_KEY = 'wxappToken';
const WX_ACCOUNT_TOKEN_REDIS_KEY = 'wxAccountToken';
const GET_TOKEN_INTERFACE = 'https://api.weixin.qq.com/cgi-bin/token';

/**
 * 发送请求小程序 token
 */
async function requestWxappToken() {
  // 请求方式以及参数说明见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
  return new Promise((resolve, reject) => {
    request(
      {
        method: 'GET',
        url: GET_TOKEN_INTERFACE,
        qs: {
          grant_type: 'client_credential',
          appid: WX_MINIPROGRAM_APP_ID,
          secret: WX_MINIPROGRAM_SECRET
        }
      },
      (error, response, body) => {
        if (error) {
          console.log(`接口地址: ${GET_TOKEN_INTERFACE}`);
          console.log(
            '接口请求参数',
            JSON.stringify({
              grant_type: 'client_credential',
              appid: WX_MINIPROGRAM_APP_ID,
              secret: WX_MINIPROGRAM_SECRET
            })
          );
          console.log('获取小程序token请求失败', error);
          reject(error);
          return;
        }
        resolve(body);
      }
    );
  });
}

/**
 * 获取微信小程序开放接口 token
 * redis 缓存 2 小时
 */
export async function getWxappToken(noredis) {
  // 查看redis中是否存在token值
  const wxTokenInRedis = await redis.get(WXAPP_TOKEN_REDIS_KEY);
  if (wxTokenInRedis && !noredis) {
    return wxTokenInRedis;
  } else {
    let newToken = await requestWxappToken();
    if (typeof newToken === 'string') {
      newToken = JSON.parse(newToken);
    }
    if (newToken.access_token) {
      // 存储新的token
      redis.set(WXAPP_TOKEN_REDIS_KEY, newToken.access_token, 'EX', 2 * 60 * 60);
      return newToken.access_token;
    } else {
      console('getWxappToken 获取token失败');
      return '';
    }
  }
}

/**
 * 发送请求，请求公众号 token
 */

async function requestWxAccountToken() {
  // 请求方式以及参数说明见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
  return new Promise((resolve, reject) => {
    request(
      {
        method: 'GET',
        url: GET_TOKEN_INTERFACE,
        qs: {
          grant_type: 'client_credential',
          appid: WX_ACCOUNT_APPID,
          secret: WX_ACCOUNT_APP_SECRET
        }
      },
      (error, response, body) => {
        if (error) {
          console.log(`接口地址: ${GET_TOKEN_INTERFACE}`);
          console.log(
            '接口请求参数',
            JSON.stringify({
              grant_type: 'client_credential',
              appid: WX_ACCOUNT_APPID,
              secret: WX_ACCOUNT_APP_SECRET
            })
          );
          console.log('获取公众号token请求失败', error);
          reject(error);
          return;
        }
        resolve(body);
      }
    );
  });
}

/**
 * 获取公众号开放接口 token
 * redis 缓存 2 小时
 */
export async function getWxAccountToken(noredis) {
  // 查看redis中是否存在token值
  const wxTokenInRedis = await redis.get(WX_ACCOUNT_TOKEN_REDIS_KEY);
  if (wxTokenInRedis && !noredis) {
    return wxTokenInRedis;
  } else {
    let newToken = await requestWxAccountToken();
    if (typeof newToken === 'string') {
      newToken = JSON.parse(newToken);
    }
    if (newToken.access_token) {
      // 存储新的token
      redis.set(WX_ACCOUNT_TOKEN_REDIS_KEY, newToken.access_token, 'EX', 2 * 60 * 60);
      return newToken.access_token;
    } else {
      console('getWxAccountToken 获取token失败');
      return '';
    }
  }
}
